package com.dx.wx.service.impl;

import com.dx.wx.service.DxShopService;
import com.dx.wx.service.DxUserService;
import com.dx.wx.util.DxUtil;
import com.ejlchina.data.Array;
import com.ejlchina.data.ListArray;
import com.ejlchina.data.Mapper;
import com.yf.response.R;
import com.yf.response.RRException;
import com.yf.utils.DateUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DxShopServiceImpl implements DxShopService {

    @Override
    public Array findShopByName(String name, String appId) {
        Map filterData = new HashMap();
        filterData.put("field_name", "name");
        filterData.put("field_values", name);
        filterData.put("operator", "LIKE");
        filterData.put("limit", 100);
        Map appIdFilter = DxUtil.addAppIdFilter(appId);
        Map sf = new HashMap();
        sf.put("field_name", "status__c");
        sf.put("field_values", 2);
        sf.put("operator", "N");
        Map data = DxUtil.createSearchData(filterData, sf, appIdFilter);
        data.put("dataObjectApiName", "AccountObj");
        return DxUtil.findSimple(data);
    }


    public void validateLink(String appId, Map map, Long phone) {
        //有些数据必填
        validate(map, "goods_price__c", "field_9akKB__c", "field_1kDya__c", "send_type__c", "done_date__c");
        //查重
        String name = (String) map.get("name");
        Array array = findShopByName(name, appId);
        if (array.size() > 0) {
            array.forEach((index, data) -> {
                if (data.toMapper().getString("name").equals(name)) {
                    throw new RRException("数据已存在!");
                }
            });
        }
        //保有量
        Array array1 = findLink(phone, appId);
        if (array1.size() >= getMaxLink()) {
            throw new RRException("超过保有量");
        }
    }

    public void validate(Map map, String... keys) {
        for (String key : keys) {
            if (map.get(key) == null || map.get(key).equals("")) {
                throw new RRException("请完整填写数据" + key);
            }
        }
    }

    @Value("${wx.mini.link.max}")
    private Integer maxLink;

    public Integer getMaxLink() {
        return maxLink;
    }

    @Override
    public void saveLink(Long phone, Map map, String appId) {
        if (map.get("_id") != null && !map.get("_id").equals("")){ //新增
            //判断是否是同一用户
            Mapper tem = findShopById((String) map.get("_id"));
            if( !map.get("user_phone__c").equals(phone)){
                throw new RRException("禁止操作!");
            }
        }
        Mapper admin = DxUtil.getUserInfo("18588004404"); //统一放到芳姐名下
        String adminId = admin.getString("openUserId");
        //创建连锁或者药店 AccountObj
        //客户类型 池田
        map.put("record_type", "record_61aCG__c");
        map.put("user_phone__c", phone);//申请人手机号
        Mapper userMapper = userService.findByMobile(phone.toString(),appId);
        if (userMapper != null) {
            String role6_phone__c = userMapper.getString("field_5h7D5__c"); //上级
            Mapper role6 = userService.findByMobile(role6_phone__c,appId);
            if(role6==null){
                throw new RRException(role6_phone__c+"用户不存在");
            }
            String role6_name__c = role6.getString("field_W1MfE__c");
            String role5_phone__c = userMapper.getString("field_rtIpu__c"); //上上级
            String name = userMapper.getString("field_W1MfE__c"); //名字
            map.put("role6_phone__c", role6_phone__c);
            map.put("role6_name__c", role6_name__c);
            map.put("role5_phone__c", role5_phone__c);
            map.put("user_name__c", name);
        }
        //时间转换
        try {
            if (map.get("_id") != null && !map.get("_id").equals("")) { //新增的
                Object date = map.get("done_date__c");
                if(date instanceof String){ //时间是String
                    map.put("done_date__c", DateUtil.strToDate(map.get("done_date__c") + " 00:00:00"));
                }else {
                    map.put("done_date__c", date);
                }
            } else {
                validateLink(appId, map, phone);
                map.put("done_date__c", DateUtil.strToDate(map.get("done_date__c") + " 00:00:00"));
            }
        } catch (ParseException e) {
            throw new RRException("日期格式错误");
        }
//        shopData.put("parent_account_id",map.get("linkId"));
        map.put("status__c", 0);
        map.put("app_id__c", appId);
        map.put("owner", Arrays.asList(adminId));
        Map data = DxUtil.createMergeData(map);
        data.put("dataObjectApiName", "AccountObj");
        if (map.get("_id") != null && !map.get("_id").equals("")) {//重新审核
            if (map.get("status__c").equals("2")) { //不是拒绝的
                throw new RRException("禁止修改!");
            }
            DxUtil.update(data);
        } else {
            Mapper mapper = DxUtil.save(data);
            map.put("_id", mapper.getString("dataId"));
        }
        updateLinkProductPrice(map, adminId);
    }

    //更新连锁的产品
    private void updateLinkProductPrice(Map map, String adminId) {
        //通过ID找打客户
        Mapper mapper = findShopById((String) map.get("_id"));
        //根据连锁ID查找
        Map filter = new HashMap();
        filter.put("field_name", "link__c");
        filter.put("field_values", map.get("_id"));
        filter.put("operator", "EQ");
        Map data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "object_C271Z__c");
        Array array = DxUtil.findSimple(data);
        //把原来的修改删除
        array.forEach((index, item) -> {
            Map temMap = new HashMap();
            temMap.put("_id", item.toMapper().getString("_id"));
            //重置客户编号与客户ID
            temMap.put("link__c", "");
            temMap.put("link_no__c", "");
            Map da = DxUtil.createMergeData(temMap);
            da.put("dataObjectApiName", "object_C271Z__c");
            DxUtil.update(da);
        });

        //插入新的
        Object obj = map.get("goods_price__c");
        if (obj != null && !obj.equals("")) {
            for (String s : ((String) obj).split(",")) {
                Map tem = new HashMap();
//                tem.put("link__c", map.get("_id"));
                tem.put("link__c", map.get("_id"));//同步客户Id
//                tem.put("link_no__c", mapper.getString("account_no"));//同步客户编号
                tem.put("link_no__c", mapper.getString("_id"));//同步客户编号
                tem.put("product__c", s.split("-")[0]);
                tem.put("price__c", s.split("-")[1]);
                tem.put("owner", Arrays.asList(adminId));
                Map da = DxUtil.createMergeData(tem);
                da.put("dataObjectApiName", "object_C271Z__c");
                DxUtil.save(da);
            }
        }

    }


    @Override
    public void updateLinkDate(Map map) {
        Map data = DxUtil.createMergeData(map);
        data.put("dataObjectApiName", "AccountObj");
        DxUtil.update(map);
    }

    @Resource
    private DxUserService userService;

    @Override
    public Array findLink(Long phone, String appId, Long startDate, Long endDate) {
        Mapper mapper = userService.findByMobile(String.valueOf(phone), appId);
        String role = mapper.getString("field_Rh3vp__c");
        Map filterData = new HashMap();
        if (role.equals("5")) { //项目总监
            filterData.put("field_name", "role5_phone__c");
        } else if (role.equals("6")) { //区域经理
            filterData.put("field_name", "role6_phone__c");
        } else {
            //如果是业务员
            filterData.put("field_name", "user_phone__c");
        }

        filterData.put("field_values", phone);
        filterData.put("operator", "EQ");
        Map appIdFilter = DxUtil.addAppIdFilter(appId);

        Map data;
        if (startDate == null) {
            //很久以前
            startDate = System.currentTimeMillis() - 10000 * 60 * 24 * 30 * 1 * 1000L;
            endDate = System.currentTimeMillis();
        }
        if (startDate != null && endDate != null) {
            Map dateStartFilter = new HashMap();
            Map dateEndFilter = new HashMap();
            //传入时间
            dateStartFilter.put("field_name", "create_time");
            dateStartFilter.put("field_values", Arrays.asList(startDate));
            dateStartFilter.put("operator", "GTE");//大于等于
            dateEndFilter.put("field_name", "create_time");
            dateEndFilter.put("field_values", Arrays.asList(endDate));
            dateEndFilter.put("operator", "LTE");//小于等于s
            data = DxUtil.createSearchData(filterData, appIdFilter, dateStartFilter, dateEndFilter);
        } else {
            data = DxUtil.createSearchData(filterData, appIdFilter);
        }

//        data.put("dataObjectApiName", "AccountObj");
        data.put("dataObjectApiName", "object_C271Z__c"); //从连锁开发申请获取
        return DxUtil.findSimple(data);
    }

    @Override
    public Mapper findLinkByName(String name,String appId) {
        Map filterData = new HashMap();
        filterData.put("field_name", "name");
        filterData.put("field_values", name);
        filterData.put("operator", "EQ");
        Map appIdFilter = DxUtil.addAppIdFilter(appId);
        Map data = DxUtil.createSearchData(filterData, appIdFilter);
        data.put("dataObjectApiName", "AccountObj");
        return DxUtil.findOne(data);
    }

    @Override
    public Array findLink(Long phone, String appId) {
        Map filterData = new HashMap();
        filterData.put("field_name", "user_phone__c");
        filterData.put("field_values", phone);
        filterData.put("operator", "EQ");
        Map appIdFilter = DxUtil.addAppIdFilter(appId);
        Map data = DxUtil.createSearchData(filterData, appIdFilter);
        data.put("dataObjectApiName", "AccountObj");
        return DxUtil.findSimple(data);
    }

    @Override
    public Array findLinkListByName(String appId, String name) {
        Map nameFilter = null;
        if(name!=null&&!name.equals("")){
            nameFilter = new HashMap();
            nameFilter.put("field_name", "field_9akKB__c");
            nameFilter.put("field_values", name);
            nameFilter.put("operator", "LiKE");
        }
        Map appIdFilter = DxUtil.addAppIdFilter(appId);
        Map data = DxUtil.createSearchData(nameFilter, appIdFilter);
        data.put("dataObjectApiName", "AccountObj");
        return DxUtil.findSimple(data);
    }

    public Mapper findShopById(String Id) {
        Map filterData = new HashMap();
        filterData.put("field_name", "_id");
        filterData.put("field_values", Id);
        filterData.put("operator", "EQ");
        filterData.put("limit", 100);
        Map data = DxUtil.createSearchData(filterData);
        data.put("dataObjectApiName", "AccountObj");
        return DxUtil.findOne(data);
    }

    @Autowired
    private DxUserService dxUserService;

    @Override
    public Array findShop(Long phone) {
        Mapper mapper = dxUserService.findByMobile(String.valueOf(phone));
        Map filter = new HashMap();
        if (mapper.getInt("field_Rh3vp__c") == 2) {//主管
            filter.put("field_name", "field_1DP0b__c"); //主管手机号
        } else {
            filter.put("field_name", "field_6CzSk__c"); //代表手机号
        }
        filter.put("field_values", Arrays.asList(phone));
        filter.put("operator", "EQ");
        Map sf = new HashMap();
        sf.put("field_name", "status__c");
        sf.put("field_values", 2);
        sf.put("operator", "N");
        Map data = DxUtil.createSearchData(filter, sf);
        data.put("dataObjectApiName", "AccountObj");
        return DxUtil.findSimple(data);
    }

    @Override
    public Mapper findLinkByAccountNo(String accountNo, String appId) {
        Map filter = new HashMap();
        filter.put("field_name", "account_no");
        filter.put("field_values", accountNo);
        filter.put("operator", "EQ");
        Map appIdFilter = DxUtil.addAppIdFilter(appId);
        Map data = DxUtil.createSearchData(filter, appIdFilter);
        data.put("dataObjectApiName", "AccountObj");
        return DxUtil.findOne(data);
    }

    @Override
    public Array findMyLink(Long phone,String appId) {
        //找到当前人
        Mapper userMapper = dxUserService.findByMobile(String.valueOf(phone), appId);
        Map filter = new HashMap();
        //查看用户级别
        if (userMapper.getInt("field_Rh3vp__c") == 5) {//总监
            filter.put("field_name", "role5_phone__c");
            filter.put("field_values", phone);
        } else if (userMapper.getInt("field_Rh3vp__c") == 6) {//经理
            filter.put("field_name", "role6_phone__c");
            filter.put("field_values", phone);
        } else {
            filter.put("field_name", "user_phone__c");
            filter.put("field_values", phone);
        }
        filter.put("operator", "EQ");
        Map data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "object_C271Z__c");
        return DxUtil.findSimple(data);
    }

    @Override
    public Array findShopByTop(Long phone) {
        Map filter = new HashMap();
        filter.put("field_name", "field_6CzSk__c"); //代表手机号
        filter.put("field_values", Arrays.asList(phone));
        filter.put("operator", "EQ");
        Map sf = new HashMap();
        sf.put("field_name", "status__c");
        sf.put("field_values", 2);
        sf.put("operator", "N");
        Map data = DxUtil.createSearchData(filter, sf);
        data.put("dataObjectApiName", "AccountObj");
        return DxUtil.findSimple(data);
    }

    @Override
    public Array findShopByLinkShop(String[] linkIds) {
        Map filter = new HashMap();
        filter.put("field_name", "parent_account_id"); //代表手机号
        filter.put("field_values", linkIds);
        filter.put("operator", "IN");
        Map data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "AccountObj");
        return DxUtil.findSimple(data);
    }

    @Override
    public void updateOwner(String userId, String[] shopIds) {
        Mapper mapper = dxUserService.findById(userId);
        String mobile = mapper.getString("field_z79am__c");
        mapper = DxUtil.getUserInfo(mobile);
        String openUserId = mapper.getString("openUserId");
        for (String shopId : shopIds) {
            Mapper shop = findShopById(shopId);
            Map data = DxUtil.createChangeOwnerData(openUserId, shop.getString("_id"));
            data.put("dataObjectApiName", "AccountObj");
            DxUtil.changeOwner(data);
        }
    }

    @Override
    public Array findPrice(Long phone) {
        Mapper mapper = dxUserService.findByMobile(String.valueOf(phone));
        String shopId = mapper.getString("field_7Q38t__c");
        return findPrice(shopId);

    }

    @Override
    public Array findPriceByShopId(String Id) {
        return findPrice(Id);
    }

    @Override
    public Array findPrice(String shopId) {
        Mapper shop = findShopById(shopId);
        //1-可售客户AvailableAccountObj通过客户account_id查找可售范围available_range_id
        Map filter = new HashMap();
        filter.put("field_name", "account_id");
        filter.put("field_values", shop.getString("_id"));
        filter.put("operator", "EQ");
        Map data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "AvailableAccountObj");
        Mapper range = DxUtil.findOne(data);
        if (range == null) {//可售范围为空  直接通过名字查询
            return findPriceByName(shop.getString("name"));
        }

        //2-可售价目表AvailablePriceBookObj 通过可售范围available_range_id查找价目表price_book_id
        filter = new HashMap();
        filter.put("field_name", "available_range_id");
        filter.put("field_values", range.getString("available_range_id"));
        filter.put("operator", "EQ");
        data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "AvailablePriceBookObj");
        Mapper Price = DxUtil.findOne(data);
        //3-价目表明细PriceBookProductObj 通过价目表pricebook_id查找
        filter = new HashMap();
        filter.put("field_name", "pricebook_id");
        filter.put("field_values", Price.getString("price_book_id"));
        filter.put("operator", "EQ");
        data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "PriceBookProductObj");
        Array prices = DxUtil.findSimple(data);
        return prices;
    }

    @Override
    public Array findPriceByName(String name) {
        //找到同名价目表 PriceBookObj
        Map price = new HashMap();
        price.put("field_name", "name");
        price.put("field_values", name);
        price.put("operator", "EQ");
        Map data = DxUtil.createSearchData(price);
        data.put("dataObjectApiName", "PriceBookObj");
        Mapper priceMapper = DxUtil.findOne(data);
        //找到价目表明细 PriceBookProductObj
        Map priceDetail = new HashMap();
        priceDetail.put("field_name", "pricebook_id");
        if (priceMapper == null || priceMapper.getString("_id") == null) {
            return new ListArray();
        }
        priceDetail.put("field_values", priceMapper.getString("_id"));
        priceDetail.put("operator", "EQ");
        data = DxUtil.createSearchData(priceDetail);
        data.put("dataObjectApiName", "PriceBookProductObj");
        return DxUtil.findSimple(data);
    }

    @Override
    public void saveShop(Long phone, Map map) {
        Mapper admin = DxUtil.getUserInfo(String.valueOf(phone));
        String adminId = admin.getString("openUserId");
        //创建连锁或者药店 AccountObj
        Map shopData = new HashMap();
        //客户类型
        String accountType = (String) map.get("accountType");
        if (map.get("accountType") != null && !map.get("accountType").equals("")) { //药店
            shopData.put("account_type", accountType);
            //业务类型药店
            shopData.put("record_type", "record_nuakr__c");
        } else {
            //业务类型总部
            shopData.put("record_type", "default__c");
        }
        shopData.put("parent_account_id", map.get("linkId"));
        shopData.put("status__c", 0);
        shopData.put("name", map.get("name"));
        shopData.put("address", map.get("address"));
        shopData.put("owner", Arrays.asList(adminId));
        Map data = DxUtil.createMergeData(shopData);
        data.put("dataObjectApiName", "AccountObj");
        String shopId = DxUtil.save(data).getString("dataId");
        if (map.get("productList") != null) {
            for (Map goodsMap : (List<Map>) map.get("productList")) {
                //创建拟售产品 goods_temp__c
                Map goodsData = new HashMap();
                goodsData.put("product_name__c", goodsMap.get("name"));
                goodsData.put("shop__c", shopId);
                goodsData.put("stand_price__c", goodsMap.get("point"));
                goodsData.put("owner", Arrays.asList(adminId));
//        priceData.put("dataObjectApiName","PriceBookObj");
                data = DxUtil.createMergeData(goodsData);
                data.put("dataObjectApiName", "goods_temp__c");
                DxUtil.save(data);
            }

        }


//        //创建价目表 PriceBookObj
//        Map priceData = new HashMap();
//        priceData.put("name",map.get("name"));
//        priceData.put("link_shop__c",shopId);
//        priceData.put("owner",Arrays.asList(adminId));
////        priceData.put("dataObjectApiName","PriceBookObj");
//        data = DxUtil.createMergeData(priceData);
//        Map detail = new HashMap();
//        detail.put("PriceBookProductObj",createPriceDetail((List<Map>) map.get("productList"),adminId));
//        data.put("details",detail);
//        data.put("dataObjectApiName","PriceBookObj");
//        DxUtil.save(data);


        //自己添加可售范围 我们新增会提示价目表为空
//        String priceId = DxUtil.save(DxUtil.createMergeData(shopData)).getString("dataId");
//        //创建可售范围AvailableRangeObj
//        Map rang = new HashMap();
//        rang.put("name",map.get("name"));
//        rang.put("owner",Arrays.asList(adminId));
//        data = DxUtil.createMergeData(rang);
//        //可售价目表
//        detail = new HashMap();
//        Map rangPrice = new HashMap();
//        rangPrice.put("price_book_id",priceId);
//        rangPrice.put("owner",Arrays.asList(adminId));
//        detail.put("AvailablePriceBookObj",Arrays.asList(rangPrice));
//        data.put("detail",detail);
//        data.put("dataObjectApiName","AvailableRangeObj");
//        DxUtil.save(data);
    }

    private List<Map> createPriceDetail(List<Map> productList, String adminId) {
        return productList.stream().map(product -> {
            Map map = new HashMap();
            map.put("product_id", product.get("_id"));
            map.put("owner", adminId);
            map.put("pricebook_sellingprice", product.get("point"));
            return map;
        }).collect(Collectors.toList());
    }

    @Override
    public void checkShop(String id, Integer type) {
        Map data = new HashMap();
        data.put("_id", id);
        data.put("status__c", type);
        Map map = DxUtil.createMergeData(data);
        map.put("dataObjectApiName", "AccountObj");
        DxUtil.update(map);
    }

    @Override
    public Array findTempGoods(String id) {
        Map filter = new HashMap();
        filter.put("field_name", "shop__c");
        filter.put("field_values", id);
        filter.put("operator", "EQ");
        Map data = DxUtil.createSearchData(filter);
        data.put("dataObjectApiName", "goods_temp__c");
        return DxUtil.findSimple(data);
    }

    //更新药店
    @Override
    public void update(Map map) {
        Map data = new HashMap();
        data.put("_id", map.get("_id"));
        map.put("address", map.get("address"));
        map.put("field_HpB1G__c", map.get("field_HpB1G__c"));
        map.put("dataObjectApiName", "AccountObj");
        DxUtil.update(DxUtil.createMergeData(map));
    }
}
